#include "wifiiot_gpio.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_gpio_gpio.h"
#include "iot_gpio_func.h"


/* GPIO初始化复用为GPIO功能 */
u32 GpioInitGpio(u32 pin)
{
    /* 根据输入参数GPIO引脚号初始化 */
    u32 ret = IoTGpioInit(pin);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTGpioInit failed :%#x \r\n", ret);
        return ret;
    }
    
    /* 根据引脚号确定引脚GPIO功能配置值 */
    u8 pinFunc = 0;
    ret = Gpio2Gpio(pin, &pinFunc);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("Gpio2Gpio failed :%#x \r\n", ret);
        return ret;
    }
    
    /* 设置复用为GPIO功能 */
    ret = IoTGpioSetFunc(pin, pinFunc);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTGpioSetFunc failed :%#x \r\n", ret);
        return ret;
    }

    /* 设置成输出有效，通过输出高电平控制 */
    ret = IoTGpioSetDir(pin, IOT_GPIO_DIR_OUT);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTGpioSetDir failed :%#x \r\n", ret);
        return ret;
    }

    return KP_ERR_SUCCESS;
}

/* GPIO输出高低电平控制 */
u32 GpioCtrlGpio(u32 pin, u32 state)
{
    u32 ret = KP_ERR_SUCCESS;
    
    switch (state) {
        case GPIO_OUT_LOW:
        case GPIO_OUT_HIGH:
        {
            /* 输出低电平控制 */
            ret = IoTGpioSetOutputVal(pin, state);
            if(ret != KP_ERR_SUCCESS){ 
                IOT_PRINTF_FUNC("IoTGpioSetOutputVal failed :%#x \r\n", ret);
                return ret;
            }
            break;
        }
        default:
        {
            IOT_PRINTF_FUNC("Invalid state :%d \r\n", state);
            return KP_ERR_FAILURE;
        }
    }

    return KP_ERR_SUCCESS;
}

